﻿using System;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using TSB.FarmPowerShellWizard.ControlTemplates.TSB.FarmPowerShellWizard;
using TSB.FarmPowerShellWizard.Repository;

namespace TSB.FarmPowerShellWizard.Layouts.TSB.FarmPowerShellWizard
{
    public partial class PSW_WebApps : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            btnGoWebApps.Click += new EventHandler(btnGoWebApps_Click);

            if (!IsPostBack)
            {
                var war = new WebApplicationRepository();

                var webApps = war.GetWebApplications();
                
                foreach(var wa in webApps)
                {
                    ddWebApplications.Items.Add(new ListItem
                                                    {
                                                        Text = wa.Name,
                                                        Value = wa.Id.ToString()
                                                    });
                }
            }
        }

        void btnGoWebApps_Click(object sender, EventArgs e)
        {
            var webAppId = new Guid(ddWebApplications.SelectedValue);
            var webApplicationRepository = new WebApplicationRepository();
            SetPowerShellText(webApplicationRepository.GetWebApplicationScript(webAppId));
        }

        void SetPowerShellText(string script)
        {
            if (string.IsNullOrEmpty(script))
            {
                phScriptContainer.Visible = false;
                txtPowerShell.Text = string.Empty;
                return;
            }

            phScriptContainer.Visible = true;
            txtPowerShell.Text = script;
        }
    }
}
